//
//  IMFowardController.m
//  wanzhaoIM
//
//  Created by wanzhao on 15/7/29.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "IMFowardController.h"

#import "GroupMenberCell.h"
#import "SettingNormalCell.h"
#import "ContactVC.h"
#import "UIImageView+WebCache.h"
#import "CContactModel.h"
#import "CDepartmentModel.h"
#import "CDepartmentMgr.h"
#import "CXmppRequestMgr.h"
#import "CContactMgr.h"
#import "NSArray+PinYin.h"
#import "GroupMemberDetailVC.h"
#import "CFileModel.h"
#import "ChildHoodService.h"
#import "CFolderMgr.h"
#import "CMessageMgr.h"
#import "CMessageModel.h"
#import "MicroDef.h"
#import "JKAlertDialog.h"
#import "IMFowardContactController.h"
#import "ChildHoodMessage.h"
#import "CGroupMgr.h"
#import "CGroupModel.h"
#import "CHChatRoomBase.h"
#import "UIBarButtonItem+category.h"
#import "CMessageDraftMgr.h"
#import "CMessageDraft.h"

#define KSECTIONHEIGHT 35.0f
#define KNORMALCELLHEIGHT 60.0f

@interface IMFowardController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *contactList;
@property (nonatomic, strong) CContactModel *curUser;

@end

@implementation IMFowardController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (NSMutableArray *)contactList
{
    if (_contactList == nil) {
        _contactList = [NSMutableArray array];
    }
    return _contactList;
}



- (void)dealloc
{

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
//UISearchDisplayDelegate
- (void)viewDidLoad
{
    [super viewDidLoad];
    CContactMgr *conMgr = [[CContactMgr alloc] init];
    CGroupMgr *groupMgr = [[CGroupMgr alloc] init];
    
    self.curUser = [conMgr loadCurContact];
    NSMutableArray *arrayM = [NSMutableArray array];
    NSArray *messagearray = [[[CMessageMgr alloc] init] loadmessageList];
    NSArray *draftArray = [[[CMessageDraftMgr alloc]init] loadAllmessageDraft];
    if (draftArray.count > 0) {
        for (CMessageDraft *draft in draftArray) {
            if (draft.MessageContent.length > 0) {
                [arrayM addObject:draft];
            }
        }
    }
    if (messagearray.count > 0) {
        for (CMessageModel *message in messagearray) {
            [arrayM addObject:message];
            for (CMessageDraft *draft in draftArray) {
                if ([draft.FriendUserId isEqualToString:message.FriendUserId] && draft.MessageContent.length > 0) {
                    [arrayM removeObject:message];
                }
            }
        }
        
    }
    
    NSArray *array = [arrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"TimeStamp" ascending:YES]]];
    
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
            if (obj.GroupId.length > 3) {
                            CGroupModel *groupModel = [groupMgr loadGroup:obj.GroupId];
                            if (groupModel != nil) {
                                [self.contactList addObject:groupModel];
                
                            }
            } else {
                CContactModel *model = [conMgr loadContactWithUserId:obj.FriendUserId];
                if(model != nil) {
                    if ([model.UserID isEqualToString:self.curUser.UserID]) {
                        model.UserName = @"我的电脑";
                    }
                    [self.contactList addObject:model];
                }
            }
           
        }];

        

    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"发送至"];
    
    
     self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"取消" target:self sel:@selector(cancel) titleFont:Font18 titleColor:WhiteColor];
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.bounds;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.sectionIndexBackgroundColor = ClearColor;
    _tableView.sectionIndexTrackingBackgroundColor = ClearColor;
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
}

- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
   
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }

    
    _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, HARDWARE_SCREEN_HEIGHT - 64);
    
    
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
        NSInteger rows = 0;
        switch (section) {
            case 0:
                rows = 1;
                break;
            case 1:
                rows = self.contactList.count;
                break;
            default:
                rows = 0;
                break;
        }
        return rows;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    return 2;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *NormalCellIdentifier = @"SettingNormalCell";
    SettingNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
    if (normalCell == nil) {
        normalCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingNormalCell" owner:self options:nil] objectAtIndex:0];
    }
    //bug 8833 fixed by lixu
    if (indexPath.section == 0) {
        normalCell.rightArrow.hidden = NO;
        normalCell.imageView.hidden = YES;
        normalCell.detailTextLabel.hidden = YES;
        [normalCell.textLabel setText:[self titleName:indexPath]];
        normalCell.textLabel.hidden = NO;
        [normalCell.titleLabel setText:@""];
        normalCell.icon.layer.cornerRadius = 5.0f/2;
        normalCell.icon.layer.masksToBounds = YES;
        [normalCell.icon setImage:nil forState:UIControlStateNormal];
        return normalCell;
        
    } else {
        
        id lastContact = self.contactList[indexPath.row];
        if ([lastContact isKindOfClass:[CGroupModel class]]) {
            CGroupModel *groupModel = (CGroupModel *)lastContact;
            if (groupModel.groupType) {
                [normalCell.icon setImage:[UIImage imageNamed:@"icon-discussList"] forState:UIControlStateNormal];
            } else {
               [normalCell.icon setImage:[UIImage imageNamed:@"icon-Group"] forState:UIControlStateNormal];
            }
            normalCell.textLabel.hidden = YES;
            normalCell.icon.layer.cornerRadius = 5.0f/2;
            normalCell.icon.layer.masksToBounds = YES;
            [normalCell.titleLabel setText:[NSString stringWithFormat:@"%@(%zd)",groupModel.GroupName,groupModel.UserNum]];
            if(indexPath.section == 1 && indexPath.row == 0)
            {
                [normalCell.seperatorLine setHidden:NO];
            }
            else
            {
                [normalCell.seperatorLine setHidden:YES];
            }
            return normalCell;
            
        } else {
          CContactModel *contact = (CContactModel *)lastContact;
            static NSString *NormalCellIdentifier = @"GroupMenberCell";
            GroupMenberCell *groupMemberCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
            if (groupMemberCell == nil) {
                groupMemberCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupMenberCell" owner:self options:nil] objectAtIndex:0];
            }
            if (![self.curUser.UserID isEqualToString:contact.UserID]) {
                if ([contact.yuLiuZiduan3 isEqualToString:@"isKefu"] && contact.isDel == 0) {
                    [groupMemberCell.icon setImage:[UIImage imageNamed:@"head-kefu"]];
                } else {
                  [groupMemberCell.icon sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contact.UserID]] placeholderImage:[UIImage imageNamed:@"80-80"]];
                }
                
            } else {
                [groupMemberCell.icon setImage:[UIImage imageNamed:@"icon-iMAC"]];
            }
            
           
            [groupMemberCell.titleLabel setText:contact.UserName];
            NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
            groupMemberCell.Arrow.hidden = NO;
            if(indexPath.row == rows - 1)
            {
                [groupMemberCell.seperatorLine setHidden:YES];
            } else {
                groupMemberCell.seperatorLine.hidden = NO;
            }
            return groupMemberCell;

        }
    }
}

-(NSString *)titleName:(NSIndexPath *)indexPath
{
    NSString *title = nil;
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    title = @"创建新的聊天";
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            title = @"最近聊天";
        }
            break;
        default:
            break;
    }
    return title;
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (_tableView == tableView) {
        
        CGFloat height = 0;
        switch (section) {
            case 1:
                height = KSECTIONHEIGHT;
                break;
            case 2:
                height = KSECTIONHEIGHT;
                break;
            case 3:
                height = KSECTIONHEIGHT;
                break;
            default:
                break;
        }
        return height;
    } else {
        return KSECTIONHEIGHT;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0;
    switch (section) {
        case 1:
            height = 0.01f;
            break;
        default:
            break;
    }
    return height;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    if (_tableView == tableView) {
        
    }
    UIView *headerView = nil;
    if(section == 0)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    UILabel *label = [[UILabel alloc] init];
    [label setText:@"最近联系人"];
    [label setTextColor:RGBCOLOR(0x92, 0x92, 0x92)];
    label.frame = CGRectMake(15, 1, 200, KSECTIONHEIGHT-1);
    [headerView addSubview:label];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        CGFloat height = KNORMALCELLHEIGHT;
        
        if(indexPath.row == 0 && indexPath.section == 0)
        {
            height = KNORMALCELLHEIGHT;
        }
        return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
            switch (indexPath.section) {
                case 0:
                {
                    switch (indexPath.row) {
                        case 0:
                        {
                            [self showContactVC];
                        }
                            break;
                        default:
                            break;
                    }
                }
                    break;
                    
                    
                case 1:
                {
                    
                    CContactModel *currentUser = [[[CContactMgr alloc] init] loadContactWithUserId:[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId];
                    id lastContact = [self.contactList objectAtIndex:indexPath.row];
                    if ([lastContact isKindOfClass:[CContactModel class]]) {
                        CContactModel *member = (CContactModel *)lastContact;
                        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"确定发送给:" message:member.UserName];
                        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                        [self fowardWithMember:member withCurUser:currentUser];
                        }];
                        
                        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
                            
                        }];
                        [alert show];
                    } else {
                        CGroupModel *model = (CGroupModel *)lastContact;
                        //bug 6086 fixed by 荣则兵
                        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"确定发送给:" message:[NSString stringWithFormat:@"%@(%zd)",model.GroupName,model.UserNum]];
                        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                            
                             [self fowardWithGroup:model withCurUser:currentUser];
                            
                        }];
                        
                        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
                            
                        }];
                        [alert show];

                    }

                }
                    break;
                    
                default:
                    break;
            }
            
}


-(void)showContactVC
{
    IMFowardContactController *departDetail = [[IMFowardContactController alloc] init];
    //    CHSNavigationController *departDetailNav = [[CHSNavigationController alloc] initWithRootViewController:departDetail];
    //    [self.leveyTabBarController presentViewController:departDetailNav animated:YES completion:nil];
    [self.navigationController pushViewController:departDetail animated:YES];
    
    
}

-(void)fowardWithGroup:(CGroupModel *)group withCurUser:(CContactModel *)currentUser
{
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
    CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
    chat.group = group;
    chat.member = nil;
    
    UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *vc = rotNav.childViewControllers[1];
    [rotNav popToViewController:vc animated:NO];
    
    [rotNav pushViewController:chat animated:YES];
    if ([ChildHoodService defaultService].forwardText !=nil) {
        [[CXmppRequestMgr shareInstance] sendMessageWithMessage:[ChildHoodService defaultService].forwardText messageId:nil curUser:currentUser member:nil group:group];
    }
    if ([ChildHoodService defaultService].fileModel == nil && [ChildHoodService defaultService].imgLocalFilePath.length > 0) {
        UIImage *image = [UIImage imageWithContentsOfFile:[ChildHoodService defaultService].imgLocalFilePath];
        [[CXmppRequestMgr shareInstance] sendImageMessage:image messageId:nil index:0 curUser:currentUser member:nil group:group fileName:nil];
        //            [self cancel];
    } else {
        [[CXmppRequestMgr shareInstance] sendFile:[ChildHoodService defaultService].fileModel messageId:nil curUser:currentUser member:nil group:group];
        //            [self cancel];
    }


}


-(void)fowardWithMember:(CContactModel *)member withCurUser:(CContactModel *)currentUser
{
    [self dismissViewControllerAnimated:NO completion:^{
       
    }];
    CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
    chat.member = member;
    chat.group = nil;
    
    UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *vc = rotNav.childViewControllers[1];
    [rotNav popToViewController:vc animated:NO];
    
    [rotNav pushViewController:chat animated:YES];
    if ([ChildHoodService defaultService].forwardText !=nil) {
        [[CXmppRequestMgr shareInstance] sendMessageWithMessage:[ChildHoodService defaultService].forwardText messageId:nil curUser:currentUser member:member group:nil];
    }
    if ([ChildHoodService defaultService].fileModel == nil && [ChildHoodService defaultService].imgLocalFilePath.length > 0) {
        UIImage *image = [UIImage imageWithContentsOfFile:[ChildHoodService defaultService].imgLocalFilePath];
        [[CXmppRequestMgr shareInstance] sendImageMessage:image messageId:nil index:0 curUser:currentUser member:member group:nil fileName:nil];
        //            [self cancel];
    } else {
        [[CXmppRequestMgr shareInstance] sendFile:[ChildHoodService defaultService].fileModel messageId:nil curUser:currentUser member:member group:nil];
        //            [self cancel];
    }

}


@end
